package com.libui.navigatonbar

import android.graphics.Canvas
import android.graphics.Paint
import android.text.TextPaint
import android.text.TextUtils
import android.text.style.ReplacementSpan
import android.widget.TextView
import kotlin.math.roundToInt

class TitleSpan(private val textView: TextView) : ReplacementSpan() {
    override fun getSize(
        paint: Paint,
        text: CharSequence?,
        start: Int,
        end: Int,
        fm: Paint.FontMetricsInt?
    ): Int {
        val textViewWidth = textView.layoutParams.width
        val titleWidth = text?.let {
            val title: String = it.subSequence(start, end).toString()
            paint.measureText(title, start, end).roundToInt()
        } ?: 0

        return if (titleWidth > textViewWidth) textViewWidth else titleWidth
    }

    override fun draw(
        canvas: Canvas,
        text: CharSequence,
        start: Int,
        end: Int,
        x: Float,
        top: Int,
        y: Int,
        bottom: Int,
        paint: Paint
    ) {
        var title = text.subSequence(start, end).toString()
        val titleWidth = paint.measureText(title)
        val textViewWidth = textView.layout.width
        if (textViewWidth < titleWidth) {
            title = TextUtils.ellipsize(
                title,
                TextPaint(paint),
                textViewWidth.toFloat(),
                TextUtils.TruncateAt.END
            ).toString()
        }
        canvas.drawText(title, start, title.length, x, y.toFloat(), paint)
    }
}